package cfunc

import (
	"fmt"
	"io"
	"log"
	"os"
	"os/exec"
	"runtime"
	"strings"
)

// ExecShell
/**
 *  @Author: rym 2024-01-16 16:35:05
 *  @Description:执行命令行方法
 *  @param strCommand
 *  @return string
 */
func ExecShell(strCommand string) string {
	var (
		name, arg string
		outBytes  []byte
		err       error
	)

	switch runtime.GOOS {
	case "linux":
		name, arg = "sh", "-c"
	case "windows":
		name, arg = "cmd", "/C"
	default:
		name, arg = "sh", "-c"
	}

	cmd := exec.Command(name, arg, strCommand)

	stdout, _ := cmd.StdoutPipe()
	if err = cmd.Start(); err != nil {
		fmt.Println("Execute failed when Start:"+err.Error(), "--", strCommand)
		return ""
	}

	outBytes, err = io.ReadAll(stdout)
	if err != nil {
		log.Fatal(err)
	}

	err = stdout.Close()
	if err != nil {
		log.Fatal(err)
	}

	if err = cmd.Wait(); err != nil {
		fmt.Println("Execute failed when Wait:"+err.Error(), "--", strCommand)
		return ""
	}
	return strings.Trim(strings.Trim(string(outBytes), ""), "\n")
}

// CWFile
/**
 *  @Author: rym 2024-01-16 16:35:14
 *  @Description:创建文件并写入内容
 *  @param dir
 *  @return err
 */
func CWFile(dir, content string) (err error) {
	file, err := os.Create(dir)

	defer file.Close()

	file.WriteString(content)

	return
}
